package com.example.petstore_2.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.petstore_2.common.CommonResponse;
import com.example.petstore_2.domain.Admin;
import com.example.petstore_2.mapper.AdminMapper;
import com.example.petstore_2.util.CryptoUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service("adminService")
public class AdminService {
    @Autowired
    private AdminMapper adminMapper;
    public Admin findByUsernameAndPassword(String username, String password) {
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("adminname", username).eq("password", CryptoUtil.SHA256(password)); // 注意：实际开发中应使用加密的密码
        return adminMapper.selectOne(queryWrapper);
    }
    public Admin findByPhoneNumber(String phoneNumber) {
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phonenumber", phoneNumber);
        return adminMapper.selectOne(queryWrapper);
    }
    public CommonResponse<Admin> updateAdmin(Admin admin) {
        UpdateWrapper<Admin> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("adminname", admin.getAdminname());
        int rowsAffected = adminMapper.update(admin, updateWrapper);
        if(rowsAffected > 0) {
            return CommonResponse.creatForSuccess(admin);//判断是否更新成功
        }
        else {
            return CommonResponse.creatForError();
        }
    }
    public List<Admin> getAdminList() {
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        return adminMapper.selectList(queryWrapper);
    }
    public CommonResponse deleteAdminById(String adminId) {
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("adminname", adminId);
        int res = adminMapper.delete(queryWrapper);
        if (res > 0) {
            return CommonResponse.creatForSuccess();
        }else {
            return CommonResponse.creatForError("删除失败！");
        }
    }
    public CommonResponse<Admin> createAdmin(Admin admin) {
        int res = adminMapper.insert(admin);
        if(res > 0) {
            return CommonResponse.creatForSuccess(admin);
        }
        else {
            return CommonResponse.creatForError();
        }
    }


}
